package com.wangsd.web.api.controller;

import com.alibaba.fastjson.JSON;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.util.SignUtils;
import com.wangsd.common.basicbean.MyController;
import com.wangsd.common.utils.BaseUtils;
import com.wangsd.common.utils.MD5Utils;
import com.wangsd.web.api.service.NotifyService;
import com.wangsd.web.mqpay.entity.Passageway;
import com.wangsd.web.mqpay.entity.Trade;
import com.wangsd.web.mqpay.service.PassagewayService;
import com.wangsd.web.mqpay.service.TradeService;
import com.wangsd.web.sys.entity.SysCompany;
import com.wangsd.web.sys.service.SysCompanyService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedHashMap;
import java.util.Map;

@Api(tags = "接口管理")
@RestController
@RequestMapping("/api/notify")
@Slf4j
public class NotifyController extends MyController {

    @Autowired
    private NotifyService notifyService;
    @Autowired
    private TradeService tradeService;
    @Autowired
    private SysCompanyService companyService;
    @Autowired
    private PassagewayService passagewayService;

    /**
     * test
     * 测试回调
     */
    @RequestMapping("/testNotify")
    public String testNotify(@RequestBody Map request) {
        log.info(JSON.toJSONString(request));
        return "success";
    }

    @RequestMapping("/nongye")
    public String nongye(@RequestParam Map<String, String> map) {
        String returnStr = "fail";
        log.debug("农业支付回调==" + JSON.toJSONString(map));
        String ip = BaseUtils.getIpAddress(request);
        log.debug("农业支付回调 ip(47.104.197.168)==" + ip);
        String back_order_sn = map.get("back_order_sn");
        String order_sn = map.get("order_sn");
        String pay_status = map.get("pay_status");
        double cost_amount = Double.parseDouble(map.get("cost_amount")) * 100;
        Trade trade = tradeService.selectByOutTradeNo(back_order_sn);
        double amount = trade.getAmount().doubleValue();
        if ("47.104.197.168".equals(ip) && "1".equals(pay_status) && amount == cost_amount) {
            returnStr = notifyService.noticeAndUpdate(trade, order_sn);
        }
        return returnStr;
    }

    @RequestMapping("/wxNative")
    public String wxNative(@RequestBody String requestBody) {
        String returnXml = "<xml>"
                + "<return_code><![CDATA[SUCCESS]]></return_code>"
                + "<return_msg><![CDATA[OK]]></return_msg>"
                + "</xml> ";
        log.debug("微信native支付回调报文==" + requestBody);
        Map map = BaseUtils.doXMLParse(requestBody);
        String returnCode = (String) map.get("return_code");
        String resultCode = (String) map.get("result_code");
        String outTradeNo = (String) map.get("out_trade_no");
        String transactionId = (String) map.get("transaction_id");
        int totalFee = Integer.parseInt(map.get("total_fee").toString());
        String wxSign = (String) map.get("sign");
        String mchId = (String) map.get("mch_id");
        if (WxPayConstants.ResultCode.SUCCESS.equals(returnCode)//执行结果成功
                && WxPayConstants.ResultCode.SUCCESS.equals(resultCode)) {//业务结果成功
            Trade trade = tradeService.selectByOutTradeNo(outTradeNo);
            SysCompany company = companyService.selectByWxMchId(mchId);
            String mySign = SignUtils.createSign(map, "MD5", company.getWxMchKey(), new String[0]);
            if (wxSign.equals(mySign) && totalFee == trade.getAmount()) {//签名验证成功
                String returnStr = notifyService.noticeAndUpdate(trade, transactionId);
                returnXml = returnXml.replace("SUCCESS", returnStr.toUpperCase());
            }
        }
        return returnXml;
    }

    @RequestMapping("/dafa")
    public String dafa(@RequestParam Map<String, String> map) {
        String returnStr = "fail";
        log.debug("大发支付回调:" + JSON.toJSONString(map));
        String sign = request.getParameter("sign");
        log.debug("大发支付回调sign:" + sign);
        Map<String, String> data = new LinkedHashMap();
        data.put("order_number", request.getParameter("order_number"));
        data.put("platform_order_number", request.getParameter("platform_order_number"));
        data.put("money", request.getParameter("money"));
        data.put("order_money", request.getParameter("order_money"));
        data.put("poundage", request.getParameter("poundage"));
        data.put("pay_state", request.getParameter("pay_state"));
        data.put("pay_time", request.getParameter("pay_time"));

        Trade trade = tradeService.selectByOutTradeNo(data.get("order_number"));
        Passageway passageway = passagewayService.selectByPayCode(trade.getPayCode());
        String mySign = MD5Utils.getSha256Sign(data, passageway.getPassword(), 1);
        double order_money = Double.parseDouble(map.get("order_money")) * 100;
        if (mySign.equals(sign) && trade.getAmount().doubleValue() == order_money) {
            returnStr = notifyService.noticeAndUpdate(trade, data.get("order_number"));
        }
        return returnStr;
    }

}
